/*
 * Copyright (c) 2024. hallele, Inc All rights reserved.
 */

package cn.hallele.ms.portalcenter.application.action.auth.login.flow;

import cn.hallele.infrastructure.metadata.exception.children.ActionException;
import cn.hallele.infrastructure.metadata.exception.children.SecurityException;
import cn.hallele.infrastructure.util.DateUtil;
import cn.hallele.mc.sdk.usercenter.common.enums.UserStatusEnum;
import cn.hallele.ms.infrastructure.plugin.safety.encoder.PasswordEncoder;
import cn.hallele.ms.portalcenter.application.action.auth.login.LoginApplicationService;
import cn.hallele.ms.portalcenter.application.bo.AuthBO;
import cn.hallele.ms.portalcenter.application.bo.UserBO;
import cn.hallele.ms.portalcenter.application.das.UserBDDas;
import cn.hallele.ms.portalcenter.integration.common.constants.POCMsgCodeConst;
import cn.hallele.ms.starter.web.framework.node.ServiceFlow;
import com.yomahub.liteflow.annotation.LiteflowComponent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Date;

/**
 * 校验用户
 *
 * @author anle5
 * @since 2024/12/31 22:54
 */
@Slf4j
@LiteflowComponent
public class VerifyUserFlow extends ServiceFlow {
    @Autowired
    private UserBDDas userBDDas;

    @Autowired
    private PasswordEncoder encoder;

    @Override
    public void process() throws Exception {
        AuthBO authBO = this.getRequestData();
        String username = authBO.getUsername();
        String password = authBO.getPassword();

        UserBO userBO = userBDDas.queryUserFullInfo(username);
        if (userBO == null) {
            log.error("User not found.");
            throw new ActionException(POCMsgCodeConst.LOGIN_FAIL);
        }

        if (!encoder.matches(password, userBO.getPassword())) {
            log.error("Password not correct.");
            throw new ActionException(POCMsgCodeConst.LOGIN_FAIL);
        }

        // 安全起见，校验完password之后要清理password
        userBO.setPassword(null);

        UserStatusEnum status = userBO.getStatus();
        if (UserStatusEnum.NORMAL != status) {
            log.error("User status is not normal.");
            throw new ActionException(POCMsgCodeConst.USER_EXCEPTION);
        }

        Date accountExpiredTime = userBO.getAccountExpiredTime();
        if (DateUtil.isExpired(accountExpiredTime)) {
            log.error("User already expired.");
            throw new ActionException(POCMsgCodeConst.USER_EXCEPTION);
        }

        Date passExpiredTime = userBO.getPassExpiredTime();
        if (DateUtil.isExpired(passExpiredTime)) {
            log.error("Password already expired.");
            throw new SecurityException(POCMsgCodeConst.USER_EXCEPTION);
        }

        this.getActionContext().setParams(LoginApplicationService.LOGIN_USER, userBO);
    }
}
